package com.augurit.common.system.web.org;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.base.extmodel.BasicCombo;
import com.augurit.common.base.extmodel.base.BaseTreeNode;
import com.augurit.common.base.extmodel.base.ITreeNode;
import com.augurit.common.base.extmodel.inner.OrgTreeNode;
import com.augurit.common.constant.OrgConstant;
import com.augurit.common.system.convert.OmOrgConverter;
import com.augurit.common.system.convert.OmPositionConverter;
import com.augurit.common.system.service.org.IAcRoleService;
import com.augurit.common.system.service.org.IOmOrgService;
import com.augurit.common.system.service.org.IOmPositionService;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.common.system.web.org.form.OmPositionForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.ExtUtils;
import com.augurit.gzcgwsp.sendNotice.service.IUserForFxService;

/**
 * 机构用户管理Action类
 */
@SuppressWarnings("serial")
@Results({
	@Result(name = ExtCrudActionSupport.RELOAD, location = "om-org.action", type = "redirect"),
	@Result(name = ExtCrudActionSupport.SUCCESS, location = "/common/system/org/om-org.jsp")
})
public class OmOrgAction extends ExtCrudActionSupport<OmOrgForm> {
	
	// Service 引用
	@Autowired
	private IOmOrgService omOrgService;
	@Autowired
	private IOmPositionService omPositionService;
	@Autowired
	private IAcRoleService acRoleService;
	@Autowired
	private IUserForFxService userForFxService;
	
	
	// 基本属性
	private Page<OmOrgForm> page = new Page<OmOrgForm>();
	private OmOrgForm omOrgForm;

	private Long orgId;
	private Long[] orgIds;
	
	private Long roleId;
	private Long[] roleIds;


	/**
	 * 跳转至JSP页面
	 */
	public String list() throws Exception {
		return SUCCESS;
	}

	/**
	 * 按条件查询机构
	 */
	public String searchOrg() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omOrgService.searchOrg(this.getLoginUserId(), omOrgForm, page, 
				WebContextUtils.getSysCodeBuffer(this.getApplication()));
		this.extRenderGridJson(page);
		return null;
	}

	/**
	 * 根据父机构ID获取直属子机构列表
	 */
	public String getOrgsByParentOrgId() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		omOrgService.getChildOrgs(orgId, page,
				WebContextUtils.getSysCodeBuffer(this.getApplication()));
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 新增或编辑机构页面
	 */
	@Override
	public String input() throws Exception {
		this.extRenderFormJson(omOrgForm);
		return null;
	}

	/**
	 * 获取主管岗位列表
	 */
	public String getDirectorPosNames()throws Exception{
		List<OmPositionForm> list = this.omPositionService.getPositionsByOrgId(orgId);
		List<BasicCombo> comboList = OmOrgConverter.convertPosListToBasicCombo(list, true);
		this.extRenderListJson(comboList, true);
		return null;
	}

	/**
	 * 获取主管人员列表
	 */
	public String getDirectorUserNames()throws Exception{
		List<OmUserForm> list = this.omOrgService.getUsers(orgId);
		List<BasicCombo> comboList = OmOrgConverter.convertUserListToBasicCombo(list, true);
		this.extRenderListJson(comboList, true);
		return null;
	}
	
	/**
	 * 移动用户到机构
	 */
	public String moveUserToOrg()throws Exception{
		String userIdStr = this.getRequest().getParameter("userId");
		String oldOrgIdStr = this.getRequest().getParameter("oldOrgId");
		String targetOrgIdStr = this.getRequest().getParameter("targetOrgId");
		this.omOrgService.moveUserToOrg(Long.valueOf(userIdStr), Long.valueOf(oldOrgIdStr), Long.valueOf(targetOrgIdStr));
		this.extRenderSuccess();
		return null;
	}

	/**
	 * 移动用户到岗位
	 */
	public String moveUserToPosition()throws Exception{
		String userIdStr = this.getRequest().getParameter("userId");
		String oldPosIdStr = this.getRequest().getParameter("oldPosId");
		String targetPosIdStr = this.getRequest().getParameter("targetPosId");
		
		Long oldPosId = oldPosIdStr != null && oldPosIdStr.trim().length() > 0 ? Long.valueOf(oldPosIdStr) : null;
		this.omOrgService.moveUserToPosition(Long.valueOf(userIdStr), oldPosId, Long.valueOf(targetPosIdStr));
		this.extRenderSuccess();
		return null;
	}

	/**
	 * 移动机构到机构
	 */
	public String moveOrg()throws Exception{
		String orgIdStr = this.getRequest().getParameter("orgId");
		String parentOrgIdStr = this.getRequest().getParameter("parentOrgId");
		Long parentOrgId = parentOrgIdStr.equals(ITreeNode.ROOT_ID) ? null : Long.valueOf(parentOrgIdStr);
		this.omOrgService.moveOrg(Long.valueOf(orgIdStr), parentOrgId);
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 保存机构信息
	 */
	@Override
	public String save() throws Exception {
		this.omOrgService.save(omOrgForm);
		//同步组织机构
		if(StringUtils.isBlank(omOrgForm.getOrgSeq())){//同步新增组织机构
			userForFxService.saveOrganization(omOrgForm);
		}else{//同步修改组织机构
			userForFxService.updateOrganization(omOrgForm);
		}		
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 删除一个或多个机构
	 */
	@Override
	public String delete() throws Exception {
		this.omOrgService.deleteOrgCascade(orgIds);
		this.extRenderSuccess();
		return null;
	}
	
	/**
	 * 根据当前用户权限查找指定机构的直属子机构列表
	 */
	public String getCanManageAndAuthOrgs()throws Exception{
		List result = null;
		
		// 根节点
		if(BaseTreeNode.isRootNode(orgId)){
			List<OmOrgForm> topOrgs = omOrgService.getCanManageAndAuthTopOrgs(this.getLoginUserId());
			result = OmOrgConverter.convertToExtNode(topOrgs);
		}
		// 普通机构节点
		else{
			List<OmOrgForm> childOrgs = omOrgService.getCanManageAndAuthChildOrgs(this.getLoginUserId(), orgId);
			result = OmOrgConverter.convertToExtNode(childOrgs);
		}
		
		// 输出JSON字符串
		this.extRenderListJson(result, false);
		return null;
	}
	
	/**
	 * 根据当前用户权限获取机构树节点的子节点（子机构、岗位、用户）列表
	 */
	public String getChildrenByPriv()throws Exception{
		List<OrgTreeNode> result = null;

		// 根据Request参数构造OrgTreeNode对象
		OrgTreeNode orgTreeNode = OrgTreeNode.build(this.getRequest());
		
		// 机构节点
		if(orgTreeNode.getPartyType().equals(OrgConstant.PARTY_TYPE_ORG)){

			// 根节点
			if(OrgTreeNode.isRootNode(orgTreeNode.getOrgId())){
				List<OmOrgForm> list = omOrgService.getCanManageTopOrgs(this.getLoginUserId());
				result = OmOrgConverter.convertToTreeNode(list);
			}
			// 普通机构节点
			else{
				OmOrgForm form = this.setExtendAttElements(this.getLoginUserId(), orgTreeNode.getOrgId());
				result = OmOrgConverter.convertToTreeNodeListByPriv(form);
			}
		}
		// 岗位节点
		else if(orgTreeNode.getPartyType().equals(OrgConstant.PARTY_TYPE_POSITION)){
			OmPositionForm form = omPositionService.getPosRelateElement(orgTreeNode.getPosId());
			result = OmPositionConverter.convertChildListToTreeNodeList(form);
		}
		
		// 输出JSON字符串
		this.extRenderListJson(result, false);
		return null;
	}
	
	/**
	 * 根据机构ID获取关联的直属元素并存放到Form的几个LIST属性中
	 * @param orgId 机构主键
	 * @return 
	 */
	private OmOrgForm setExtendAttElements(Long curUserId, Long orgId){
		OmOrgForm form = omOrgService.get(orgId);
		form.setChildren(omOrgService.getCanManageChildOrgs(curUserId, orgId));
		form.setUsers(omOrgService.getUsersWithNoPostion(curUserId, orgId));
		form.setPostions(omOrgService.getPositions(curUserId, orgId));
		return form;
	}
	
	/**
	 * 获取与指定角色关联的机构
	 * @author 王剑文
	 */
	public String getOrgsByRole() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		acRoleService.getOrgsByRole(page, roleId, WebContextUtils.getSysCodeBuffer(this.getApplication()));
		this.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 获取与指定角色不关联的机构
	 * @author 王剑文
	 */
	public String getOrgsNotAssociateRole() throws Exception{
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		acRoleService.getOrgsNotAssociateRole(page, roleId, omOrgForm, WebContextUtils.getSysCodeBuffer(this.getApplication()));
		this.extRenderGridJson(page);
		return null;
	}	
	
	
	@Override
	public void prepare() throws Exception {
	}
	
	public void prepareSearchOrg() throws Exception {
		prepareModel();
	}
	
	public void prepareGetOrgsByParentOrgId() throws Exception {
		prepareModel();
	}
	
	public void prepareInput() throws Exception {
		prepareModel();
	}
	
	public void prepareSave() throws Exception {
		prepareModel();
	}
	
	public void prepareGetOrgsByRole() throws Exception {
		prepareModel();
	}
	
	public void prepareGetOrgsNotAssociateRole() throws Exception {
		prepareModel();
	}

	public OmOrgForm getModel(){
		return omOrgForm;
	}
	
	@Override
	protected void prepareModel() throws Exception {
		if(orgId != null)
			omOrgForm = omOrgService.get(orgId);
		else
			omOrgForm = new OmOrgForm();
	}
	
	
	// 属性getter和setter方法
	public Long getOrgId() {
		return orgId;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}

	public Page<OmOrgForm> getPage() {
		return page;
	}

	public void setPage(Page<OmOrgForm> page) {
		this.page = page;
	}

	public Long[] getOrgIds() {
		return orgIds;
	}

	public void setOrgIds(Long[] orgIds) {
		this.orgIds = orgIds;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public Long[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Long[] roleIds) {
		this.roleIds = roleIds;
	}
}
